package com.weds.frame.auth.service;

import com.alibaba.fastjson2.JSON;
import com.weds.frame.auth.constants.AuthConstant;
import com.weds.frame.auth.entity.ScBusinessOptApiCache;
import com.weds.frame.auth.mapper.ScBusinessOptApiAuthMapper;
import com.weds.frame.auth.mapper.ScBusinessOptAuthMapper;
import com.weds.frame.core.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Description:
 * Author: LiuWenQing
 * Datetime: 2023/4/4 15:42
 */
@Service
public class CommCacheAuthService {

    @Autowired
    private RedisUtil redisUtils;
    @Autowired
    private ScBusinessOptApiAuthMapper scBusinessOptApiAuthMapper;
    @Autowired
    private ScBusinessOptAuthMapper scBusinessOptAuthMapper;


    public void initOptApiList(){
        String searchKey = AuthConstant.REDIS_OPT;
        List<ScBusinessOptApiCache> ls = scBusinessOptApiAuthMapper.selectAll();
        //清空
        redisUtils.dels(redisUtils.getScanKeys(AuthConstant.REDIS_OPT + ":*"));
        for(ScBusinessOptApiCache opt : ls){
            redisUtils.put(searchKey+":"+opt.getOptApi(), JSON.toJSONString(opt));
        }
    }

    public ScBusinessOptApiCache getOptByApi(String apiName, Integer refreshIfNotExits) {
        String searchKey = AuthConstant.REDIS_OPT + ":"+apiName;
        Object res = redisUtils.get(searchKey);
        if(res==null){
            if(refreshIfNotExits==null || 1==refreshIfNotExits) {
                refreshOptByApi(apiName);
                return getOptByApi(apiName,0);
            }
            return null;
        }
        return JSON.parseObject(res.toString(),ScBusinessOptApiCache.class);
    }

    //刷新api操作信息
    public void refreshOptByApi(String apiName) {
        String searchKey = AuthConstant.REDIS_OPT + ":"+apiName;
        ScBusinessOptApiCache scBusinessOpt = scBusinessOptAuthMapper.selectByOptApi(apiName);
        if (scBusinessOpt == null){
            redisUtils.del(searchKey);
            return;
        }
        redisUtils.put(searchKey, JSON.toJSONString(scBusinessOpt));
    }

}
